import dayjs from 'dayjs';
import { CategoryModel } from '~/server/models/category.model';

// 更新分类
export default defineEventHandler(async (event) => {
	try {
		const body = await readBody(event);

		const { id, name, description } = body;

		if (!id || !name || !description) {
			return { code: 0, message: '参数不完整' };
		}

		const exist = await CategoryModel.findOne({ name, _id: { $ne: id } });

		if (exist) {
			return { code: 0, message: '分类名称已存在' };
		}

		await CategoryModel.findByIdAndUpdate(id, {
			name,
			description,
			updatedAt: dayjs().format('YYYY年MM月DD日 HH:mm:ss'),
		});

		return { code: 1, message: '更新成功' };
	} catch (error: any) {
		return { code: 0, message: error.message };
	}
});
